<?php
// 检查食材匹配情况的脚本

// 数据库配置
$host = '127.0.0.1';
$dbname = 'yingyang';
$username = 'root';
$password = 'root';
$charset = 'utf8mb4';

try {
    $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== 食材匹配检查 ===\n\n";
    
    // 获取一些示例食材名称
    echo "从食材关联表中获取一些示例食材名称:\n";
    $stmt = $pdo->query('SELECT DISTINCT ingredient_name FROM fa_food_ingredientrel WHERE ingredient_name IS NOT NULL AND ingredient_name != "" LIMIT 10');
    $ingredientNames = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    foreach ($ingredientNames as $name) {
        echo "检查食材: $name\n";
        $stmt = $pdo->prepare('SELECT id, name, parent_id, categories_id FROM fa_food_ingredient WHERE name = ?');
        $stmt->execute([$name]);
        $ingredient = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($ingredient) {
            echo "  ✓ 找到匹配: ID={$ingredient['id']}, parent_id={$ingredient['parent_id']}, categories_id={$ingredient['categories_id']}\n";
        } else {
            echo "  ✗ 未找到匹配\n";
            
            // 尝试模糊匹配
            $stmt = $pdo->prepare('SELECT id, name, parent_id, categories_id FROM fa_food_ingredient WHERE name LIKE ? LIMIT 3');
            $stmt->execute(["%$name%"]);
            $fuzzyMatches = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if (!empty($fuzzyMatches)) {
                echo "  ~ 模糊匹配结果:\n";
                foreach ($fuzzyMatches as $match) {
                    echo "    ID={$match['id']}, 名称={$match['name']}\n";
                }
            }
        }
        echo "\n";
    }
    
    // 统计食材匹配情况
    echo "=== 食材匹配统计 ===\n";
    $stmt = $pdo->query('SELECT COUNT(*) as total FROM fa_food_ingredientrel');
    $total = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "总关联记录数: " . $total['total'] . "\n";
    
    $stmt = $pdo->query('SELECT COUNT(*) as matched FROM fa_food_ingredientrel WHERE ingredient_id > 0');
    $matched = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "已匹配记录数: " . $matched['matched'] . "\n";
    
    $stmt = $pdo->query('SELECT COUNT(*) as unmatched FROM fa_food_ingredientrel WHERE ingredient_id = 0 OR ingredient_id IS NULL');
    $unmatched = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "未匹配记录数: " . $unmatched['unmatched'] . "\n";
    
} catch (Exception $e) {
    echo "执行失败: " . $e->getMessage() . "\n";
}
?>